import React, { Component, Fragment } from "react";
import TodoItem from "./TodoItem";
import "./style.css";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      inputValue: ""
    };
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            type="text"
            value={this.state.inputValue}
            onChange={this.handleInputValue}
            ref={input => {
              this.input = input;
            }}
          />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>{this.getTodoItem()}</ul>
      </Fragment>
    );
  }

  getTodoItem() {
    /* 不转义html标签， dangerouslySetInnerHTML={{__html: item}} */
    return this.state.list.map((item, index) => (
      <TodoItem
        key={index}
        item={item}
        index={index}
        onDelete={this.handleDeleteItem}
      />
      // <li key={index} onClick={() => this.handleDeleteItem(index)}>
      //   {item}
      //   {/* {item} */}
      // </li>
    ));
  }
  handleInputValue = e => {
    const value = e.target.value;
    // const value = this.input.value;
    this.setState(() => ({
      inputValue: value
    }));
    // this.setState({
    //   inputValue: e.target.value
    // });
  };
  handleBtnClick = () => {
    this.setState(prevState => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ""
    }));
    // this.setState({
    //   list: [...this.state.list, this.state.inputValue],
    //   inputValue: ""
    // });
  };
  handleDeleteItem = index => {
    this.setState(prevState => {
      let list = [...prevState.list];
      list.splice(index, 1);
      return { list };
    });
    // this.setState({
    //   list
    // });
  };
}

export default TodoList;
